package cn.nupt.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.nupt.util.DBTool;

public class SecondaryCardDAOImpl implements SecondaryCardDAO{

	@Override
	//搜索当前次卡的的最大值并返回
	public int selectMaxCardId() {
		int maxId = 0;
		Connection conn = null;
		PreparedStatement prst = null;
		ResultSet rs = null;
		String sql1 = "select * from secondarycard";
		String sql2 = "select max(card_id) as maxId from secondarycard";
		conn = DBTool.getConnection();
		try{
			prst = conn.prepareStatement(sql1);
			rs = prst.executeQuery();
			//如果当前次卡表为空
			if(!rs.next()){
				maxId = 0;
				return maxId;
			}else{//否则，找到当前次卡最大值
				rs = prst.executeQuery(sql2);
				if(rs.next()){
					maxId = rs.getInt("maxId");
				}
				
			}
			
		}catch(SQLException ex ){
			ex.printStackTrace();
		}finally{
			DBTool.close(prst, conn);	//	注意关闭数据库相关连接
		}
		return maxId;
	}

	@Override
	//插入一张新的次卡，并返回受影响的行数
	public int insertSecondaryCard(int cardId ,int leftTimes) {
		int row = 0;
		Connection conn = null;
		PreparedStatement prst = null;
		String sql = "insert into secondarycard (card_id ,start_date,left_times) values(?,?,?)";
		conn = DBTool.getConnection();
		try{
			SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
			Date date = new Date();
			String dateStr = sd.format(date);
   			prst = conn.prepareStatement(sql);
			prst.setInt(1,cardId);
			prst.setString(2,dateStr);
			prst.setInt(3,leftTimes);
			row = prst.executeUpdate();
		}catch(SQLException ex){
			ex.printStackTrace();
		}finally{
			DBTool.close(prst, conn);
		}
		return row;
	}

}
